package com.cloud.async.business.context.support;

import com.cloud.async.business.context.AbstractApplicationContext;
import com.cloud.async.business.context.data.abs.AbsDataSource;
import com.cloud.async.result.core.factory.AsyncResultFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

/**
 * @author chengr
 * @desc 可实现的底层子类（定制化定时处理结果等）,主做定制化的处理,只提工方法调用，其余均不提供（如异常处理、锁机制等）
 *
 */
public class RealizableContext extends AbstractApplicationContext {

    /**
     * logger
     */
    private final Log logger = LogFactory.getLog(getClass());

    /**
     * 抽象数据处理
     */
    private AbsDataSource absDataSource;

    @Override
    protected Boolean saveData(String key, CompletableFuture value) {
        logger.info("RealizableContext saveData start, key: " + key);
        return absDataSource.saveData(key, value);
    }

    @Override
    protected void releaseData(String key) {
        logger.info("RealizableContext releaseData start, key: " + key);
        absDataSource.releaseData(key);
    }

    @Override
    public <T> T getResult(String key) {
        return (T) absDataSource.getResult(key,getMilliSecond());
    }

    @Override
    public <T> T getResult(String key, Long milliSecond) {
        return (T) absDataSource.getResult(key, milliSecond);
    }

    @Override
    public boolean contains(String asyncKeyName) {
        return absDataSource.includeKey(asyncKeyName);
    }

    @Override
    public int getCount() {
        return absDataSource.getCount();
    }

    @Override
    public String[] getKeyNames() {
        return absDataSource.getKeyNames();
    }

    /**
     * 初始化当前数据源类型
     * @param data
     */
    private void initializeDataSource(AbsDataSource data) {
        this.absDataSource = data;
    }

    /**
     * 基于有参构造进行创建对象
     * @param executor 线程池
     * @param asyncResultFactory 结果解析
     */
    public RealizableContext(Executor executor,
                             AsyncResultFactory asyncResultFactory,
                             Long milliSecond, AbsDataSource data) {
        initializeExecutor(executor);
        initializeAsyncResultFactory(asyncResultFactory);
        initializeMilliSecond(milliSecond);
        initializeDataSource(data);
    }
}
